<?php


namespace api\modules\v1\controllers;

use services\common\ExcelExtendService;
use api\controllers\OnAuthController;
use services\common\ExcelService;
use Yii;
use yii\db\Exception;

class ExcelController extends OnAuthController
{
    public $modelClass = '';

    /**
     * 不用进行登录验证的方法
     *
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $optional = ['project-list', 'patient-info', 'del-patient-data', 'delete-oss-image','image-log','add-dengta-callback','add-dengta-patient','test','load','upload-excel','update-user','update-record','update-today-record','first-visit','visit','fault-diagnosis','update-time-record','customer-server',
        'registered-serial-no','registered-user','expense-serial-no','expense-add','in-hospital-serial-no','in-hospital','update-registration','update-expense'];


    public static function changeDb($hospital)
    {
        ini_set('max_execution_time', '0');
        //修改连接
        Yii::$app->db->close();
        Yii::$app->db->dsn = env('DB_CONNECTION') . ':host=' . env('DB_HOST') . ';dbname=' . env('DB_DATABASE_'.strtoupper($hospital));
        Yii::$app->db->open();
    }

    public static function deleteOssImage()
    {
        $params = Yii::$app->request->post();
        Yii::$app->services->patientClinicImg->deleteOssImage($params);
    }

//    /**
//     *
//     * @return array
//     * @throws \Exception
//     */
//    public static function actionLoad($hospital)
//    {
//        $redis = Yii::$app->redis;
//        $key = $hospital.'-'.'document-list';
//        //遍历文件夹记录文件
//        $dir = '/data/baiyou_data_export/' . $hospital ;
//        $new_dir = '/data/baiyou_data_export/history_files/' . $hospital;
//
//        // 创建保存目录
//        if (!file_exists($dir) && !mkdir($dir, 0777, true)) {
//            return false;
//        }
//
//        $ready = 0;
//        $money_excel = 0;
//        $guahao_excel = 0;
//        $files = array();
//        if(@$handle = opendir($dir)) { //注意这里要加一个@，不然会有warning错误提示：）
//            while(($file = readdir($handle)) !== false) {
//                if($file != ".." && $file != ".") { //排除根目录；
//
//                    if ($file == 'ready.txt') {
//                        $ready = 1;
//                        continue;
//                    }
//                    $time = mb_substr($file,-18,8);
//                    $fileInfo['time'] = $time;
//                    $fileInfo['name'] = $file;
//
//                    //判断是不是挂号
//                    $nameArray =explode('_',$file);
//                    $name = end($nameArray);
//                    $pattern = '/^money|^guahao/i';
//                    preg_match($pattern,$name,$matches);
//                    $type =  end($matches);
//
//                    if ($type == 'money') {
//                        $money_excel = 1;
//                    } elseif ($type == 'guahao') {
//                        $guahao_excel = 1;
//                    }
//
//                    $files[] = $fileInfo;
//                }
//            }
//
//            // 查询有没有计数统计
//            $logModel = HospitalLog::find()
//                ->where(['hospital' => $hospital,'function' => 'ready'])
//                ->one();
//
//            if (empty($logModel)) {
//                $logModel = new HospitalLog();
//                $logModel->hospital = $hospital;
//                $logModel->function = 'ready';
//            }
//
//            $day = date('Y-m-d', strtotime($logModel->day)).' 23:59:59';
//            $now_day = date('Y-m-d H:i:s');
//
//            //新的一天开始,重置提醒标志
//            if ($now_day > $day &&  $logModel->status = 1) {
//                $logModel->status = 0;
//                $logModel->save();
//            }
//
//            $logModel->day = $now_day;
//
//            //如果没有ready.txt
//            if ($ready == 0 || $money_excel == 0 || $guahao_excel == 0) {
//
//                $hTime = date("H");
//                // 只有在8点到18点 上班时间提醒
//                if ($hTime > 8 && $hTime < 20) {
//                    $logModel->count += 1;
//
//                    if ($logModel->count >= 3 && $logModel->status == 0) {
//                        $message = "项目: ".env($hospital).PHP_EOL."奕远日数据导入异常,请检查奕远数据同步电脑,把软件关掉重开[点击查看详情](https://shimo.im/docs/KQtTpPQ6TTjJYtG9)";
//                        $result = ExcelService::sendMessage($message,Yii::$app->params['DING_TOKEN'], Yii::$app->params['DING_KEY']);
//                        $resultArray = json_decode($result);
//
//                        // 信息发送成功更新状态
//                        if ($resultArray->errcode == '0')
//                        {
//                            $logModel->status = 1;
//                        }
//                    }
//                    $logModel->save();
//                }
//
//                return 'ready.txt 文件不存在'.PHP_EOL;
//
//            } else {
//                $logModel-> count = 0;
//                $logModel->save();
//            }
//
//            closedir($handle);
//            $keyArray = array_column($files,'time');
//            array_multisort($keyArray, SORT_ASC, $files);
//
//            foreach ($files as $value) {
//
//                $file = $value['name'];
//
//                $size = filesize($dir.'/'.$file);
//
//                //如果文件字节为0 直接删除文件
//                if ($size == 0) {
//                    unlink($dir.'/'.$file);
//                    continue;
//                }
//
//                $docList= DocumentList::find()
//                    ->where(['excel_name' => $file,'size'=>$size,'project_name'=>$hospital])
//                    ->one();
//
//                if ($docList) {
//                    $redis->hset($key,md5($file.$size),'1');
//                    unlink($dir.'/'.$file);
//                    continue;
//                }
//
//                $data = Yii::$app->services->excel->loadExcel($dir.'/'.$file, $hospital , $value['time']);
//                if ($data){
//                    // 记录日志
//                    $params = [
//                        'hospital' => $hospital,
//                        'function' => 'actionLoad',
//                        'day' => date('Y-m-d H:i:s'),
//                        'status' => 1,
//                    ];
//                    ExcelService::errorLog($params);
//
//                   $model = new DocumentList();
//                   $model->excel_name = $file;
//                   $model->created_time = time();
//                   $model->size = $size;
//                   $model->project_name = $hospital;
//                   $model->item_count_all = $data['item_count_all'];
//                   $model->item_count = $data['item_count'];
//                   $model->type = $data['type'];
//                   $model->path = $dir.'/'.$file;
//                   if ($model->save()) {
//                       $redis->hset($key,md5($file.$size),'1');
//                       //unlink($dir.'/'.$file);
//                       rename($dir.'/'.$file,$new_dir.'/'.$file);
//                   }
//               }
//            }
//
//            if ($ready == 1) {
//                unlink($dir.'/ready.txt');
//            }
//            return  $hospital .'-'. date('Y-m-d H:i:s').'-success'.PHP_EOL;
//        }
//    }

//    public function actionUploadExcel()
//    {
//        $path = Yii::$app->request->post('path');
//        $hospital = Yii::$app->request->post('hospital');
//
//        if (!is_file($path)) {
//            return CommonHelper::api(422, '文件不存在');
//        } else {
//            $data = Yii::$app->services->excel->loadExcel($path, $hospital);
//            $size = filesize($path);
//            $file = basename($path);
//
//            if (is_array($data) && $data['item_count'] > 0) {
//                //实际导入数据大于0,记录导入记录
//                $redis = \Yii::$app->redis;
//                $key = 'document-list';
//
//                $docList= DocumentList::find()
//                    ->where(['excel_name' => $file,'size'=>$size])
//                    ->one();
//                if (empty($docList)) {
//                    $model = new DocumentList();
//                    $model->excel_name = $file;
//                    $model->created_time = time();
//                    $model->size = $size;
//                    $model->item_count_all = $data['item_count_all'];
//                    $model->item_count = $data['item_count'];
//                    $model->type = $data['type'];
//                    $model->path = $path;
//                    if ($model->save()) {
//                        $redis->hset($key,md5($file.$size),'1');
//                    }
//                }
//
//            }
//            unlink($path);
//            return CommonHelper::api(200, '文件存在',$data);
//        }
//    }

    /**
     * 更新人员信息
     * day = 1 更新当天
     *
     * @param $hospital
     * @param null $day
     * @return bool
     * @throws Exception
     */
    public static function actionUpdateUser($hospital, $day = null, $endDay = null)
    {
        ExcelService::registration($hospital, $day, $endDay);
        $params = [
            'hospital' => $hospital,
            'function' => 'actionUpdateUser',
            'day' => date('Y-m-d H:i:s'),
            'status' => 1,
        ];
        ExcelService::errorLog($params);
        return  $hospital .'-'. date('Y-m-d H:i:s').'-success'.PHP_EOL;
    }

    /**
     * 更新白友,挂号记录/诊疗项目详细/诊疗项目汇总信息(所有奕远数据)
     * @param $hospital
     * @return bool
     */
    public static function actionUpdateRecord($hospital)
    {
        ini_set("memory_limit", "-1M");
        ExcelService::updateData($hospital);
        return  $hospital .'-'. date('Y-m-d H:i:s').'-success'.PHP_EOL;

    }

    /**
     * 更新白友,挂号记录/诊疗项目详细/诊疗项目汇总信息(当天奕远数据)
     * @param $hospital
     * @return bool
     */
    public static function actionUpdateTodayRecord($hospital)
    {
        $day = date('Y-m-d');
        ExcelService::updateData($hospital,$day);
        $params = [
            'hospital' => $hospital,
            'function' => 'actionUpdateTodayRecord',
            'day' => date('Y-m-d H:i:s'),
            'status' => 1,
        ];
        ExcelService::errorLog($params);
        return  $hospital .'-'. date('Y-m-d H:i:s').'-success'.PHP_EOL;
    }


    public static function actionUpdateTimeRecord($hospital,$startTime,$endTime,$type)
    {
        ExcelService::updateTimeData($hospital,$startTime,$endTime,$type);
        return  $hospital .'-'. date('Y-m-d H:i:s').'-success'.PHP_EOL;
    }
    /**
     * 更新当月挂号用户,消费不满足条件流失处理
     * 当月有消费的流失/断诊复诊处理
     *
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function actionFirstVisit($hospital)
    {
        // 当月消费达标,变成
        ExcelService::firstVisit($hospital);
         // 本月存在消费,本月之前的断诊/流失都算复诊(修改为本来有来院记录都算 复诊)
        ExcelService::loss($hospital);

        return true;
    }

    /**
     * 上个初诊->复诊
     *
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function actionVisit($hospital)
    {
        return ExcelService::visit($hospital);
    }

    /**
     * 60天未来院,算断诊
     * @param $hospital
     * @return bool
     * @throws Exception
     */
    public static function actionFaultDiagnosis($hospital)
    {
        return ExcelService::faultDiagnosis($hospital);
    }

    /**
     * v1/excel/registered-serial-no
     * 获取存入的,奕远最新id
     * @return array
     */
    public static function actionRegisteredSerialNo()
    {
        $ProjectId = Yii::$app->request->get('ProjectId');
        $serial_no = ExcelService::registeredSerialNo($ProjectId);
        return [
          'serial_no' => $serial_no,
        ];
    }

    /**
     * v1/excel/registered-user
     * 新增奕远用户数据
     */
    public static function actionRegisteredUser()
    {
        //添加挂号用户
        $params = Yii::$app->request->post();
        $params['ProjectId'] = Yii::$app->request->headers->get('ProjectId', 0);
        return ExcelService::registeredUser($params);
    }

    /**
     * v1/excel/expense-serial-no
     * 获取存入的,奕远最新消费id
     * @return array
     */
    public static function actionExpenseSerialNo()
    {
        $ProjectId = Yii::$app->request->get('ProjectId');
        $type = Yii::$app->request->get('type');
        $serial_no = ExcelService::expenseSerialNo($ProjectId,$type);
        return [
            'serial_no' => $serial_no,
        ];
    }

    /**
     * @api {get} /v1/excel/expense-add 奕远消费数据
     * @apiName expense-add
     * @apiGroup excel
     *
     * @apiParam {Number} type              类型【0门诊、1住院】
     * @apiParam {Number} SerialNo          亦远消费主键ID【type=0 tb_ChargeDetail_Clinic、type=1 tb_ChargeDetail_InHospital】
     * @apiParam {Number} InvalidName       患者姓名
     * @apiParam {Number} CardNo            患者诊疗号
     * @apiParam {Number} ItemName          药品名称
     * @apiParam {Number} ItemUnit          药品单位
     * @apiParam {Number} Amount            数量
     * @apiParam {Number} SellingPrice      售价
     * @apiParam {Number} SellingAmount     售价金额
     * @apiParam {Number} AdvantagedMoney   折后金额
     * @apiParam {Number} CategoryAName     费用名称
     * @apiParam {Number} ChargeTime        门诊消费时间【type=0有效】
     * @apiParam {Number} BefellTime        住院消费时间【type=1有效】
     * @apiParam {Number} SectionName       科室名称
     * @apiParam {Number} DoctorName        医生姓名
     */
    public static function actionExpenseAdd()
    {
        //添加挂号用户
        $params = Yii::$app->request->post();
        $params['ProjectId'] = Yii::$app->request->headers->get('ProjectId', 0);
        return ExcelService::expenseAdd($params);
    }

    /**
     * /v1/excel/in-hospital-serial-no
     * 获取,上次出院/住院的时间
     * @return array
     */
    public static function actionInHospitalSerialNo()
    {
        $ProjectId = Yii::$app->request->get('ProjectId');
        $type = Yii::$app->request->get('type');
        $serial_no = ExcelService::inHospitalSerialNo($ProjectId,$type);
        return [
            'serial_no' => $serial_no,
        ];
    }


    /**
     * /v1/excel/in-hospital
     * 存入 奕远住院/出院数据
     * @return bool
     */
    public static function actionInHospital()
    {
        //添加住院/出院信息
        $params = Yii::$app->request->post();
        $params['ProjectId'] = Yii::$app->request->headers->GET('ProjectId', 0);
        return ExcelService::inHospital($params);
    }

    /**
     * /v1/excel/update-registration
     * @apiName 更新每天的用户数据
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     */
    public static function actionUpdateRegistration()
    {
        //添加挂号用户
        $params = Yii::$app->request->post();
        $params['ProjectId'] = Yii::$app->request->headers->GET('ProjectId', 0);
        return ExcelService::updateRegistration($params);
    }

    /**
     * v1/excel/update-expense
     * @apiName 更新消费记录诊疗号
     * @author loujie
     * @return bool
     */
    public static function actionUpdateExpense()
    {
        $params = Yii::$app->request->post();
        $params['ProjectId'] = Yii::$app->request->headers->GET('ProjectId', 0);
        return ExcelService::updateExpense($params);
    }

    /**
     * @apiName 同步灯塔植发到诊患者
     * @return bool
     * @throws \yii\web\HttpException
     * @author loujie
     */
    public static function actionAddDengtaPatient()
    {
        $params = Yii::$app->request->post();
        return ExcelService::addDengtaPatient($params);
    }

    /**
     * @apiName 同步灯塔回访记录
     * @return bool
     * @throws \yii\web\HttpException
     * @author loujie
     */
    public static function actionAddDengtaCallback()
    {
        $params = Yii::$app->request->post();
        return ExcelService::addDengtaCallback($params);
    }

    /**
     * 记录各个诊室,上传图片情况
     * @return void
     */
    public function actionImageLog()
    {
        $params = Yii::$app->request->get();
        return ExcelExtendService::byImage($params);
    }

    /**
     * 项目列表
     */
    public function actionProjectList(): array
    {
        $params = Yii::$app->request->get();
        return  ExcelExtendService::projectList($params);
    }

    /**
     * 查看员工信息情况
     * @return array|mixed|\yii\db\ActiveRecord
     */
    public function actionPatientInfo()
    {
        $params = Yii::$app->request->get();
        return ExcelExtendService::patientInfo($params);
    }

    /**
     * 诊疗号不是重复诊疗号,是完全错误废弃的诊疗号,数据删除不容易恢复
     * 删除涉及诊疗号的相关数据
     *
     * @return void
     */
    public function actionDelPatientData()
    {
        $params = Yii::$app->request->post();
        return ExcelExtendService::delPatientData($params);
    }


}